﻿using System;
using System.Web.UI;
using MS.InformationManagement.Presenter.DocumentDeliveryBag;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Support;
using System.Web.UI.WebControls;
using MS.InformationManagement.Support.Constants;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support.Enums;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;

namespace MS.InformationManagement.WP.DocumentCenter.DocumentDeliveryBagList
{
    public partial class DocumentDeliveryBagListUserControl : BaseControl, IDocumentDeliveryBagView
    {
        #region [Private Fields]

        DocumentDeliveryBagPresenter _Presenter;
        DeliveryControlType _controlType;

        #endregion

        #region [Public Properties]

        public IEnumerable<Zona> DeliverZones { get; set; }

        public bool IsCapture { get { return ControlType == DeliveryControlType.Capture; } }

        public int? SelectedUserCriteria 
        { 
            get 
            { 
                return string.IsNullOrEmpty(PeopleEditorUsuario.CommaSeparatedAccounts) ? new Nullable<int>() : PeopleHelper.GetUsersFromPeopleEditor(this.PeopleEditorUsuario)[0].User.ID; 
            } 
        }

        public string DocNumberSearchCriteria
        {
            get
            {
                return txtbRadNumberSearchCriteria.Text;
            }
        }

        public string AreaSearchCriteria
        {
            get
            {
                return txtbAreaSearchCriteria.Text;
            }
        }

        public DeliveryControlType ControlType 
        {
            get
            {
                return _controlType;
            }
            set
            {
                _controlType = value;
            }
        }

        public IList<int> SelectedItemsId { get { return GetSelectedItemsId(); } }

        public List<MedioDeEnvio> DeliveryMeans
        {
            get { return Cache["DeliveryMeans"] as List<MedioDeEnvio>; }
            set { Cache["DeliveryMeans"] = value; }
        }



        #endregion

        #region [Event Handlers]

        protected void grdPendingDocuments_OnRowDataBound(Object sender, GridViewRowEventArgs e)
        {

            //Show Hide Controls

            if (ControlType == DeliveryControlType.Capture)
            {
                e.Row.Cells[5].Visible = true;
                e.Row.Cells[6].Visible = true;
                e.Row.Cells[7].Visible = true;
                e.Row.Cells[8].Visible = false;

            }

            if (ControlType == DeliveryControlType.Reception)
            {
                e.Row.Cells[5].Visible = false;
                e.Row.Cells[6].Visible = false;
                e.Row.Cells[7].Visible = false;
            }


            if (e.Row.RowType != DataControlRowType.DataRow) return; 

            //Setting delivery Means
            DropDownList deliverMeans = e.Row.FindControl("ddlDeliveryMean") as DropDownList;
            deliverMeans.DataSource = DeliveryMeans;
            deliverMeans.DataBind();
            deliverMeans.Items.Insert(0, new ListItem { Text = GlobalConstants.DDL_INITIAL_STATE, Value = "" });

            //Setting delivery zones
            DropDownList zones = e.Row.FindControl("ddlZona") as DropDownList;
            zones.DataSource = DeliverZones;
            zones.DataBind();
            zones.Items.Insert(0, new ListItem { Text = GlobalConstants.DDL_INITIAL_STATE, Value = "" });

            //Loading initial data
            DocumentoImpreso currentDocument = e.Row.DataItem as DocumentoImpreso;
            if (currentDocument == null) return;

            //Setting delivery link
            if (ControlType == DeliveryControlType.Capture)
            {
                HyperLink lnkDelivery = e.Row.FindControl("lnkRadicado") as HyperLink;
                lnkDelivery.NavigateUrl = string.Format("javascript:openDialogAutoSizeRefreshParent('/sites/docs/_layouts/MS.InformationManagement.WP/MailDeliveryConfig.aspx?dID={0}&lName={1}')", currentDocument.IdDocumento, currentDocument.BibliotecaDelDocumento);
            }

            //Configuring capture link
            HyperLink captureLink = e.Row.FindControl("lnkCapture") as HyperLink;
            captureLink.NavigateUrl = string.Format("javascript:openDialogAutoSizeRefreshParent('/sites/docs/_layouts/MS.InformationManagement.WP/ScanningManager.aspx?SelectedId={0}&RadicadoId={1}&Salida={2}&LibraryName={3}')", currentDocument.IdDocumento, currentDocument.NoRadicado, "1",currentDocument.BibliotecaDelDocumento);

            //Loading selected delivery data
            EnvíoDeCorrespondencia deliveryInfo = currentDocument.DeliveryInfo;  
            if (deliveryInfo == null) return;

            TextBox weighBox = e.Row.FindControl("txtbWeight") as TextBox;
            TextBox costBox = e.Row.FindControl("txtbCost") as TextBox;
            RadioButton localDelivery = e.Row.FindControl("rdbIsLocal") as RadioButton;
            RadioButton nalDelivery = e.Row.FindControl("rdbIsNational") as RadioButton;


            deliverMeans.SelectedIndex = deliverMeans.Items.IndexOf((from item in deliverMeans.Items.OfType<ListItem>()
                                                                     where item.Value == deliveryInfo.MedioEnvioCorreo.Id.Value.ToString()
                                                                     select item).FirstOrDefault());

            zones.SelectedIndex = zones.Items.IndexOf((from item in zones.Items.OfType<ListItem>()
                                                       where item.Value == deliveryInfo.ZonaEnvio.Id.Value.ToString()
                                                       select item).FirstOrDefault());

            weighBox.Text = deliveryInfo.PesoCorrespondencia.Value.ToString();
            costBox.Text = deliveryInfo.CostoDelEnvío.Value.ToString();
            localDelivery.Checked = deliveryInfo.EnvioLocal.HasValue ? deliveryInfo.EnvioLocal.Value : false;
            nalDelivery.Checked = deliveryInfo.EnvioNacional.HasValue ? deliveryInfo.EnvioNacional.Value : false;
        }

        protected void grdPendingDocuments_OnRowCreated(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox costControl = e.Row.FindControl("txtbCost") as TextBox;
                costControl.Numeric("999,999,999,99", true);
                DocumentoImpreso currentItem = e.Row.DataItem as DocumentoImpreso;
                Button popUpTrigger = e.Row.FindControl("btnCustomizeDelivery") as Button;

                if (e.Row.DataItem != null)
                {
                    popUpTrigger.OnClientClick = string.Format("openDialogAutoSize('/sites/docs/_layouts/Ms.InformationManagement.WP/MailDeliveryConfig.aspx?lName={0}&dID={1}');return false;"
                        , currentItem.BibliotecaDelDocumento, currentItem.IdDocumento);
                   
                    string radiobuttongroup = string.Format("rdbgroup_{0}", currentItem.Id);
                    RadioButton localDelivery = e.Row.FindControl("rdbIsLocal") as RadioButton;
                    RadioButton nationaDelivery = e.Row.FindControl("rdbIsNational") as RadioButton;

                    localDelivery.GroupName = radiobuttongroup;
                    nationaDelivery.GroupName = radiobuttongroup;
                }               
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (IsPostBack) return;
                _Presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            try
            {
                base.OnInit(e);
                //Page.RegisterAjaxLoaderPlugin();
                //btnSave.AddLoader();
                //btnSearch.AddLoader();
                _Presenter = new DocumentDeliveryBagPresenter(this);
                grdPager.OnPageChanged += new InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls.Pager.PageChangeHandler(OnPageChanged);
                grdPager.NumberOfPagesToDisplay = 5;
                txtbTotalDeliveryCost.Text = "0";
                txtbTotalDeliveryCost.Numeric("999,999,999,99", true); 
                if (_controlType == DeliveryControlType.Capture)
                {
                    RegisterJavascriptInitialization();
                    //costsResume.Visible = true;
                    btnSave.Visible = true;
                    btnSaveChanges.Visible = false;
                }

                if (_controlType == DeliveryControlType.Delivery)
                    filterContainer.Visible = false;

            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void OnPageChanged(object sender, EventArgs e)
        {
            _Presenter.FetchDeliveryPendingDocuments(false);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                _Presenter.FetchDeliveryPendingDocuments(true);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            string isDlg = Request.QueryString.Get("IsDlg");
            if (!string.IsNullOrEmpty(isDlg) && isDlg.Equals("1")) { this.CloseWindow(); }
            else { this.GoCurrentUserHome(); }
        }

        protected void OnCommandButtonClicked(object sender, Controls.CommandClickedEventArgs e)
        {

        }

        protected void btnSave_action(object sender, EventArgs e)
        { 
            try
            {
                _Presenter.SaveAction();
            }
            catch(Exception ex)
            {
                HandleError(ex);
            }  
        }

        #endregion

        #region [IDocumentDeliveryBagView Members]

        public void ShowMessate(string message)
        {
            this.ShowAlertAndClose(message);
        }

        public void ShowCaptureWeighUpControls()
        {
            btnSaveChanges.Visible = false;
            btnSave.Visible = true;
        }

        public IList<int> GetSelectedItemsId()
        {
            IList<int> selectedIds = new List<int>();
            foreach (GridViewRow row in grdPendingDocuments.Rows)
            {
                if (row.RowType != DataControlRowType.Header)
                {
                    CheckBox control = row.FindControl("chkSelectedItem") as CheckBox;

                    if (control == null)
                        throw new Exception("Se presentaron errores al obtener items seleccionados");

                    if (control.Checked)
                    {
                        HiddenField field = row.FindControl("hdfId_reception")  as HiddenField;
                        selectedIds.Add(int.Parse(field.Value));
                    }
                }
            }
            return selectedIds;
        }

        public List<SPListItem> DeliveryItems
        {
            get
            {
                return Cache["DeliveryItems"] as List<SPListItem>;
            }
            set
            {
                Cache["DeliveryItems"] = value;
                if (value == null || value.Count == 0) return;
                grdPendingDocuments.DataSource = value;   
                grdPendingDocuments.DataBind();
                grdPager.BuildPager();
            }
        }


        public List<DocumentoImpreso> PendingDocuments
        {
            get
            {
                return Cache["PendingDocuments"] as List<DocumentoImpreso>;
            }
            set
            {
                Cache["PendingDocuments"] = value;
                if (value == null || value.Count == 0) return;
                grdPendingDocuments.DataSource = value;
                grdPendingDocuments.DataBind();
                grdPager.BuildPager();
            }
        }

        public int PageIndex
        {
            get
            {
                return grdPager.PageIndex;
            }
            set
            {
                grdPager.PageIndex = value;
            }
        }

        public int PageSize
        {
            get
            {
                return grdPager.PageSize;
            }
            set
            {
                grdPager.PageSize = value;
            }
        }

        public int TotalRecords
        {
            get
            {
                return grdPager.TotalRecords;
            }
            set
            {
                grdPager.TotalRecords = value;
            }
        }

        public void ShowMessage(string message)
        {
            this.ShowAlertMessageAndRedirect(message, "/sites/docs/_layouts/Ms.InformationManagement.WP/maildeliverybag.aspx");
        }

        public void UpdateLoadData()
        { 
            _Presenter.HandleLoad();    
        }

        #endregion

        #region [Private Members]

        private void RegisterJavascriptInitialization()
        {
            StringBuilder javascript = new StringBuilder("<script type = 'text/javascript'>");
            javascript
                    .Append("$(document).ready(function () {  MS.InformationManagement.MailDeliveryConfig.InitializeMailBagGrid('")
                    .Append(grdPendingDocuments.ClientID)
                    .Append("', '")
                    .Append(txtbTotalDeliveryCost.ClientID)
                    .Append("', '")
                    .Append(txtbAreaSearchCriteria.ClientID)
                    .Append("', '")
                    .Append(btnSave.ClientID)
                    .Append("');});</script>");

            Page.ClientScript.RegisterStartupScript(this.GetType(), "javascriptinitialization", javascript.ToString(), false);
        }

        

        #endregion

    }
}
